package com.lam.common.components.easyexcel.imp.service;

import java.text.MessageFormat;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.lam.common.base.domain.BaseEntity;
import com.lam.common.components.easyexcel.imp.model.ImportBody;
import com.lam.common.components.easyexcel.imp.model.ImportEntry;
import com.lam.common.components.easyexcel.imp.model.ImportWrapper;
import com.lam.common.context.TokenUtils;
import com.lam.common.exception.BaseException;
import com.lam.common.utils.JsonUtil;
import com.lam.common.utils.StringUtils;
import com.lam.common.utils.uuid.IdUtils;

/**
 * @author lam
 *
 * @param <Ie> 用于接收数据对象的Java类
 * @param <R> 用于保存数据对象的Java类
 */
public class AbstractImportService<Ie, R extends BaseEntity> {
	
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	/**
     * 导入数据
     * @param wrapper 数据包装
     * @param importBody 导入的具体处理逻辑
     */
    public void importData(ImportWrapper<Ie, R> wrapper, ImportBody<Ie, R> importBody) {
        
        String operName = TokenUtils.getLoginUsername();
        R data;
        for (ImportEntry<Ie, R> entry : wrapper.getDataList()) {
            data = entry.getData();
            try {
                // 校验数据是否存在等需要跟数据库交互的验证操作
                R o = importBody.selectRecord(entry);
                if (o == null) {
                	data.setCreateBy(operName);
                	String msg = importBody.insertRecord(entry);
                	if(StringUtils.isNotBlank(msg)) {
                		entry.setImportResult(msg);
                    	wrapper.addFailEntry(entry);
                	}
                } else if (wrapper.isUpdateSupport()) {
                	data.setId(o.getId());
                	data.setUpdateBy(operName);
                	String msg = importBody.updateRecord(entry);
                	if(StringUtils.isNotBlank(msg)) {
                		entry.setImportResult(msg);
                    	wrapper.addFailEntry(entry);
                	}
                } else {
                	entry.setImportResult(importBody.notUniqueMsg(entry));
                	wrapper.addFailEntry(entry);
                }
            } catch (BaseException e) {
                entry.setImportResult(e.getMessage());
                wrapper.addFailEntry(entry);
            } catch (Exception e) {
                String uid = IdUtils.getUid();
                logger.error(MessageFormat.format("导入异常，data:{0}, uid:{1}", JsonUtil.toJsonString(data), uid), e);
                throw new BaseException("导入程序异常!", e);
            }
        }
    }
}
